package com.lostfigo.helloworld.controller;

import com.lostfigo.helloworld.dao.DepartmentDao;
import com.lostfigo.helloworld.dao.EmployeeDao;
import com.lostfigo.helloworld.pojo.Department;
import com.lostfigo.helloworld.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collection;

/**
 * @program: helloworld
 * @description:
 * @author: Lost_Figo
 * @create: 2020-05-12 09:49
 **/
@Controller
public class EmployeeController {

    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private DepartmentDao departmentDao;

    @RequestMapping("/emps")
    public String list(Model model){
        Collection<Employee> employees = employeeDao.getAll();
        model.addAttribute("emps",employees);
        return "emp/list";
    }

    @GetMapping("/emp")
    public String toAddpage(Model model){
        // 查出所有部门的信息
        Collection<Department> departments = departmentDao.getDepartment();

        model.addAttribute("departments",departments);
        return "emp/add";
    }

    @PostMapping("/emp")
    public String addEmp(Employee employee){

        System.out.println(employee);
        // 添加的操作
        employeeDao.save(employee);

        return "redirect:/emps";
    }

    // 员工修改页面
    @GetMapping("/emp/{id}")
    public String toUqdatepage(@PathVariable("id") Integer id,Model model){
        // 查出所有部门的信息
        Collection<Department> departments = departmentDao.getDepartment();

        model.addAttribute("departments",departments);
        Employee employee = employeeDao.getEmployeeById(id);
        model.addAttribute("emp",employee);
        return "emp/update";
    }

    @PostMapping("/updateEmp")
    public String updateEmp(Employee employee){
        Integer id = employee.getId();
        employeeDao.save(employee);

        return "redirect:/emps";
    }

    @GetMapping("/delemp/{id}")
    public String deleteEmp(@PathVariable("id") Integer id){
        employeeDao.delete(id);

        return "redirect:/emps";
    }
}
